$(function () {
    var handle = function (s) {
        var avatips;
        // hover选择默认头像
        $("#usrImg").mouseenter(function (e) {
            avatips = layer.tips("<div class='AvatarCan'></div>", '#usrImg', {
                tips: [2, '#eee'], //右边
                time: 180000
            });
            $(".layui-layer-content>div.AvatarCan").append(s);
            $(".layui-layer-content>div.AvatarCan").css({
                "max-width": "382px",
                "max-height": $("#usrImg").height(),
                "overflow": "auto"
            });

            $(".layui-layer.layui-layer-tips").mouseleave(function () {
                layer.close(avatips);
            });
            $(".layui-layer.layui-layer-tips img.userAva").click(function (e) {
                $("#usrImg").attr("src", e.target.getAttribute("src"));
                $("#usrImg").attr("serverimgID", e.target.getAttribute("serverimgID"));
                $("#usrImgFile").val("");
                $('span.filenamespan').text(langThis("mi_avatarupload"));
                layer.close(avatips);
            });
        });
        $("body").click(function () {
            layer.close(avatips);
        });
    };
    //闭包缓存默认头像
    (function (handle) {
        var imgs = [];
        if (!imgs.length) {
            $.ajax({
                url: "photos",
                type: "GET",
                contentType: "application/json",
                success: function (e) {
                    if (e && e.rows) {
                        for (var i in e.rows) {
                            var img = new Image();
                            img.setAttribute("class", "userAva");
                            //img.setAttribute("src","./photos/" + e.rows[i].id);
                            img.setAttribute("src", e.rows[i].url);
                            img.setAttribute("serverimgID", e.rows[i].id);
                            imgs.push(img);
                        }
                        handle(imgs);
                    }
                },
                error: function (event) {
                    // console.log(data);
                }
            });
        }
    })(handle);
});
function setPreImg() {
    var file = document.getElementById("usrImgFile").files[0];
    if (!file) {
        $("#usrImg").attr('src', "./imgs/useralt.png");
        return;
    }
    var fReader = new FileReader();
    fReader.onload = function (e) {
        //检查过滤图片格式
        var imgform = file.name.slice(file.name.lastIndexOf(".") + 1);
        switch (imgform.toLowerCase()) {
            case "jpg": break;
            case "jpeg": break;
            case "png": break;
            case "bmp": break;
            case "gif": break;
            default: {
                layer.msg(langThis("mi_wrongImgForm"), { icon: 2 });
                $("#usrImgFile").val("");
                return;
            }
        }
        var filename = file.name.slice(0, file.name.lastIndexOf("."));
        var data = e.target.result;
        $("#usrImg").attr('src', data);
        $("#usrImg").attr("serverimgid", "");
        // 还是用土办法吧，不支持sad.as.asd.as.d.as.d.jsp这种文件名
        // var spanString='<span class="badge">'+filepath.replace(/^.+?\\([^\\]+?).([^.\\]*?)?$/gi,"$2")+'</span> '+filepath.replace(/^.+?\\([^\\]+?)(.[^.\\]*?)?$/gi,"$1");
        $('span.filenamespan').html('<span class="badge">' + imgform + '</span> ' + filename);
    }
    fReader.readAsDataURL(file);
}
// 创建或修改账户
function CreatOrModifyAct() {
    var Uinfo = {};
    Uinfo.username = $("#loginName").val();
    Uinfo.password = UserInfo.password;
    Uinfo.name = $("#username").val();
    Uinfo.nickname = $("#nickname").val();
    Uinfo.defaultrole = $("#userDefaultRole").val();
    Uinfo.university = $("#usrSchool").val();
    Uinfo.major = $("#usrMajor").val();
    Uinfo.enteryear = $("#classYear").val();
    Uinfo.sex = $("#usrSex").val();
    //验证不能为空
    for (var i in Uinfo) {
        if (!Uinfo[i]) {
            layer.msg(langThis("myinfo_lgNameEmpty"), { icon: 0 });
            return;
        }
    }

    //验证数字
    if (isNaN(parseInt(Uinfo.enteryear))) {
        layer.msg(langThis("pm_datemustNm"), { icon: 0 });
        $("#classYear").focus();
        return;
    }
    //验证协议
    if($("#agreementCheck").prop("checked")===false){
        layer.msg(langThis("mi_agreedtip"), { icon: 0 });
        return;
    }
    //创建或修改账户
    var CoMAcc = function () {
        var serverurl = "userinfos";
        if (UserID && UserID != "null" && UserID != "") {
            serverurl = "userinfos/" + UserID;
            //无修改不提交
            var mdfflag = true;
            for (var item in UserInfo) {
                if (Uinfo[item] != UserInfo[item]) {
                    mdfflag = false;
                    break;
                }
            }
            if (mdfflag) {
                layer.closeAll();
                layer.msg(langThis("mi_OprationSucess"), { icon: 1 });
                return;
            }
        }
        $.ajax({
            url: serverurl,
            type: "POST",
            data: JSON.stringify(Uinfo),
            dataType: "json",
            contentType: "application/json",
            success: function (data) {
                layer.closeAll();
                layer.msg(langThis("mi_OprationSucess"), { icon: 1,time:1200 }, function () {
                    if(serverurl === "userinfos"){
                        location.href = "./login";
                    }
                    location.href = "./myinfo";
                });
            },
            error: function (event) {
                layer.closeAll();
                layer.msg(langThis("role_optionfaild"), { icon: 2 });
            }
        });
    };
    //头像
    var usedefaultAvatar = $("#usrImg").attr("serverimgID");
    if (!usedefaultAvatar && $("#usrImgFile").val() == "") {
        if (UserID && UserID != "null" && UserID != "") {
            Uinfo.photo = UserInfo.photo;//$("#usrImg").attr("src").split("/photos/")[1]
            CoMAcc();
        } else {
            layer.msg(langThis("myinfo_userAvatarEmpty"), { icon: 0 });
            $("#usrImgFile").focus();
        }

    } else if (usedefaultAvatar) {
        Uinfo.photo = usedefaultAvatar;
        layer.load(2, {
            shade: [0.5, "#eee"]
        });
        CoMAcc();
    } else {
        layer.load(2, {
            shade: [0.5, "#eee"]
        });
        //上传头像
        $.ajaxFileUpload({
            url: "photos",
            secureuri: false,
            type: "POST",
            fileElementId: ["usrImgFile"],
            // data: "",
            dataType: "json",
            success: function (data) {
                Uinfo.photo = data.id;
                CoMAcc();
            },
            error: function (event) {
                layer.closeAll();
                layer.msg(langThis("role_optionfaild"), { icon: 2 });
            }
        });
    }
}